<template>
  <div class="group-tour-page">
    <!-- 头部区域 -->
    <div class="group-tour-header">
      <!-- 粒子效果 -->
      <div class="header-particles">
        <div class="particle" v-for="n in 20" :key="n"></div>
      </div>
      
      <!-- 头部内容 -->
      <div class="group-tour-header-content">
        <h2>跟团探索</h2>
        <div class="group-tour-subtitle">
          <span class="subtitle-text">发现精彩</span>
          <span class="subtitle-divider">•</span>
          <span class="subtitle-text">结伴同行</span>
        </div>
        
        <!-- section-intro -->
        <div class="section-intro">
          <div class="intro-badge">精选团游</div>
          <h3>探索最受欢迎的跟团游路线</h3>
          <p>专业导游带队，轻松畅享旅程</p>
        </div>
        
        <!-- 搜索框 -->
        <div class="group-tour-search">
          <input type="text" v-model="search" placeholder="搜索跟团游..." />
        </div>
      </div>
    </div>
    
    <!-- 内容区域 -->
    <div class="group-tour-container">
      <div class="group-tour-list-wrap">
        <div class="group-tour-grid">
          <div
            class="group-tour-card"
            v-for="tour in filteredTours"
            :key="tour.groupTourID"
          >
            <!-- 图片区域 -->
            <div class="group-tour-img-container">
              <img 
                class="group-tour-img" 
                :src="tour.mainImage || 'https://picsum.photos/400/200'" 
                alt="跟团游图片" 
                @click="goToDetail(tour.groupTourID)"
              />
              <div class="img-overlay"></div>
              <!-- 状态徽章 -->
              <div :class="['status-badge', `status-${tour.progressStatus === '未开始' ? 'not-started' : tour.progressStatus === '报名中' ? 'registering' : tour.progressStatus === '报名截止' ? 'registration-closed' : tour.progressStatus === '进行中' ? 'in-progress' : tour.progressStatus === '已结束' ? 'ended' : 'default'}`]">
                {{ tour.progressStatus }}
              </div>
            </div>
            
            <!-- 卡片内容 -->
            <div class="group-tour-content-wrapper">
              <!-- 旅行社信息 -->
              <div class="group-tour-agency" @click.stop="goToAgencyDetail(tour.travelAgencyID)">
                <img class="agency-avatar" :src="tour.agencyAvatar || 'https://randomuser.me/api/portraits/men/11.jpg'" alt="旅行社头像" />
                <span class="agency-name">{{ tour.travelAgencyName }}</span>
              </div>
              
              <div class="group-tour-info">
                <h3 class="group-tour-title-card">{{ tour.groupTourName }}</h3>
                <div class="group-tour-scenic">景点：{{ tour.scenicAreaName }}</div>
                <p class="group-tour-content" v-html="tour.groupTourIntroduction"></p>
              </div>
              
              <!-- 操作按钮 -->
              <div class="group-tour-actions">
                <button
                  class="action-button collect-button"
                  @click.stop="toggleCollect(tour)"
                  :class="{ 'is-active': tour.isCollected }"
                >
                  <el-icon><Collection /></el-icon>
                  {{ tour.isCollected ? '已收藏' : '收藏' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Collection } from '@element-plus/icons-vue';

export default {
  name: "GroupTourMain",
  components: {
    Collection
  },
  data() {
    return {
      search: "",
      tours: [],
      loading: true,
      currentUserId: null,
      baseImageURL: 'http://localhost:8080/'
    }
  },
  computed: {
    filteredTours() {
      if (this.loading) return [];
      if (!this.search) return this.tours;
      const s = this.search.trim().toLowerCase();
      return this.tours.filter(
        t =>
          t.groupTourName.toLowerCase().includes(s) ||
          t.scenicAreaName.toLowerCase().includes(s) ||
          t.groupTourIntroduction.toLowerCase().includes(s) ||
          t.travelAgencyName.toLowerCase().includes(s)
      );
    }
  },
  methods: {
    async fetchInitialData() {
      this.loading = true;
      try {
        console.log('Fetching loginId from localStorage...');
        const loginId = localStorage.getItem('loginId');
        if (loginId) {
          console.log(`Fetching userId for loginId: ${loginId}`);
          const userRes = await axios.get(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
          this.currentUserId = userRes.data.userId;
          console.log(`Fetched userId: ${this.currentUserId}`);
        } else {
          console.log('No loginId found in localStorage. User not logged in or session expired.');
          this.currentUserId = null;
        }

        await this.fetchTours();

      } catch (error) {
        console.error('Error in fetchInitialData:', error);
        ElMessage.error('初始化数据失败，请检查网络或稍后再试。');
      } finally {
        this.loading = false;
        console.log('Initial data fetching process finished.');
      }
    },

    async fetchTours() {
      try {
        console.log('Fetching all group tours...');
        const response = await axios.get('http://localhost:8080/mw/GroupTourList');
        const groupTourList = response.data || [];
        console.log('Successfully fetched group tour list.');

        const processedTours = await Promise.all(groupTourList.map(async (tour) => {
          let isCollected = false;

          if (this.currentUserId && tour.groupTourID) {
            try {
              console.log(`Checking collect status for group tour ${tour.groupTourID} and user ${this.currentUserId}`);
              const collectCheckRes = await axios.get(`http://localhost:8080/mw/checkFavorite?userId=${this.currentUserId}&groupTourId=${tour.groupTourID}`);
              isCollected = collectCheckRes.data;
              console.log(`Collect status for ${tour.groupTourID}: ${isCollected}`);
            } catch (collectError) {
              console.error(`Error checking collect status for ${tour.groupTourID}:`, collectError);
            }
          } else {
            console.log(`currentUserId or groupTourID is null, skipping collect status checks for tour ${tour.groupTourID}`);
          }

          let mainImage = 'https://picsum.photos/400/200';
          if (tour.groupTourImageLinks && tour.groupTourImageLinks.length > 0) {
            mainImage = tour.groupTourImageLinks[0].startsWith('http')
              ? tour.groupTourImageLinks[0]
              : this.baseImageURL + tour.groupTourImageLinks[0];
          }

          return {
            ...tour,
            mainImage,
            isCollected,
            agencyAvatar: tour.travelAgencyAvatar || 'https://randomuser.me/api/portraits/men/11.jpg'
          };
        }));

        this.tours = processedTours;
        console.log('All group tour data processed successfully.');
        console.log('Processed Tours Data:', processedTours);

      } catch (error) {
        console.error('An unhandled error occurred while fetching group tours:', error);
        ElMessage.error('获取跟团游数据失败，请稍后再试。');
      }
    },
    goToDetail(id) {
      this.$router.push({ path: `/homepage/group-tour/detail/${id}` });
    },
    goToAgencyDetail(id) {
      this.$router.push({ path: `/homepage/agencydetail/${id}` });
    },
    async toggleCollect(tour) {
      if (!this.currentUserId) {
        ElMessage.warning('请先登录才能收藏跟团游。');
        return;
      }

      try {
        if (tour.isCollected) {
          await axios.delete(`http://localhost:8080/mw/deleteByUserAndGroupTour?userId=${this.currentUserId}&groupTourId=${tour.groupTourID}`);
          tour.isCollected = false;
          ElMessage.success('取消收藏成功！');
        } else {
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          const day = String(now.getDate()).padStart(2, '0');
          const hours = String(now.getHours()).padStart(2, '0');
          const minutes = String(now.getMinutes()).padStart(2, '0');
          const seconds = String(now.getSeconds()).padStart(2, '0');
          const formattedFavoriteTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;

          await axios.post('http://localhost:8080/mw/addGroupTourFavorite', {
            userId: this.currentUserId,
            groupTourId: tour.groupTourID,
            favoriteTime: formattedFavoriteTime
          });
          tour.isCollected = true;
          ElMessage.success('收藏成功！');
        }
      } catch (error) {
        console.error('收藏/取消收藏失败:', error);
        ElMessage.error('操作失败，请稍后再试。');
      }
    },
  },

  mounted() {
    this.fetchInitialData();
  },
}
</script>

<style scoped>
/* ========== 整体页面样式 ========== */
.group-tour-page {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
}

.group-tour-page::before {
  content: '';
  position: fixed;
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background: 
    linear-gradient(135deg, rgba(74, 144, 226, 0.8), rgba(107, 91, 149, 0.8)), 
    url('https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&auto=format&fit=crop&w=2000&q=80') center/cover;
  z-index: 0;
  pointer-events: none;
}

.group-tour-page > * {
  position: relative;
  z-index: 1;
}

.loading {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* ========== 头部样式 ========== */
.group-tour-header {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  text-align: center;
  position: relative;
  width: 100%;
  padding: 120px 20px 20px;
  overflow: hidden;
  background: none;
  min-height: auto;
}

.header-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.particle {
  position: absolute;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}

.particle:nth-child(odd) {
  animation-delay: -2s;
}

.particle:nth-child(even) {
  animation-delay: -4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); opacity: 0; }
  50% { transform: translateY(-100px) rotate(180deg); opacity: 1; }
}

.group-tour-header-content {
  position: relative;
  z-index: 2;
  margin-bottom: 30px;
  max-width: 800px;
  width: 100%;
}

.group-tour-header h2 {
  font-size: 3rem;
  font-weight: 300;
  letter-spacing: 6px;
  margin: 0;
  text-transform: uppercase;
  margin-bottom: 15px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.group-tour-subtitle {
  font-size: 1.1rem;
  font-weight: 300;
  letter-spacing: 2px;
  margin-bottom: 25px;
  opacity: 0.9;
}

.subtitle-text {
  display: inline-block;
}

.subtitle-divider {
  margin: 0 15px;
  opacity: 0.7;
}

.section-intro {
  margin-top: 15px;
  padding: 0 20px;
  margin-bottom: 25px;
}

.intro-badge {
  display: inline-block;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
  letter-spacing: 1px;
  margin-bottom: 15px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
}

.section-intro h3 {
  font-size: 1.6rem;
  font-weight: 400;
  margin: 0 0 10px 0;
  color: white;
  letter-spacing: 2px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.section-intro p {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.9);
  margin: 0 0 15px 0;
  line-height: 1.6;
  letter-spacing: 1px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
}

.group-tour-search {
  margin-bottom: 20px;
}

.group-tour-search input {
  width: 320px;
  padding: 10px 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 25px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  outline: none;
  min-width: 300px;
}

.group-tour-search input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.group-tour-search input:focus {
  border-color: rgba(255, 255, 255, 0.6);
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* ========== 内容区域 ========== */
.group-tour-container {
  position: relative;
  max-width: 1300px;
  margin: 0 auto;
  padding: 20px 60px 40px;
  background: none;
  min-height: 600px;
  z-index: 2;
}

.group-tour-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  width: 100%;
  margin-bottom: 40px;
}

@media (max-width: 1200px) {
  .group-tour-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 900px) {
  .group-tour-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 600px) {
  .group-tour-grid {
    grid-template-columns: 1fr;
  }
}

.group-tour-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  opacity: 0;
  transform: translateY(40px);
  animation: fadeInUp 0.8s ease-out forwards;
}

.group-tour-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
  background: rgba(255, 255, 255, 0.98);
}

.group-tour-img-container {
  position: relative;
  width: 100%;
  padding-bottom: 60%;
  overflow: hidden;
}

.group-tour-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.group-tour-card:hover .group-tour-img {
  transform: scale(1.05);
}

.img-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50%;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.3), transparent);
  pointer-events: none;
}

.group-tour-content-wrapper {
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 140px;
}

.group-tour-info {
  flex: 1;
  margin-bottom: 12px;
}

.group-tour-title-card {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 8px 0;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.group-tour-content {
  font-size: 14px;
  color: #737373;
  line-height: 1.4;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.group-tour-agency {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.group-tour-agency:hover {
  opacity: 0.7;
}

.agency-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #eee;
}

.agency-name {
  font-size: 1em;
  color: #409eff;
  font-weight: 500;
}

.group-tour-scenic {
  font-size: 0.9em;
  color: #888;
  margin-bottom: 8px;
}

.group-tour-actions {
  margin-top: auto;
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 6px;
  border: none;
  background: transparent;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s;
  color: #737373;
  background: #f0f4fa;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 0.9em;
}

.action-button:hover {
  background: #e6f0ff;
  transform: scale(1.05);
}

.action-button .el-icon {
  font-size: 1.2em;
}

.collect-button.is-active {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.collect-button.is-active:hover {
  background-color: #e6a23c;
  color: white;
}

/* ========== 响应式设计 ========== */
@media (max-width: 768px) {
  .group-tour-header {
    padding: 30px 15px 20px;
  }
  
  .group-tour-header h2 {
    font-size: 2.2rem;
    letter-spacing: 3px;
  }
  
  .section-intro h3 {
    font-size: 1.3rem;
  }
  
  .group-tour-search input {
    min-width: 250px;
  }
  
  .group-tour-container {
    padding: 15px 16px;
  }
  
  .group-tour-grid {
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .group-tour-header {
    padding: 25px 15px 15px;
  }
  
  .group-tour-header h2 {
    font-size: 1.8rem;
    letter-spacing: 2px;
  }
  
  .group-tour-subtitle {
    font-size: 0.95rem;
  }
  
  .group-tour-search input {
    min-width: 200px;
  }
  
  .group-tour-content-wrapper {
    padding: 16px;
    min-height: 120px;
  }
}

/* ========== 新增动画样式 ========== */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(40px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.group-tour-grid .group-tour-card:nth-child(1) { animation-delay: 0.1s; }
.group-tour-grid .group-tour-card:nth-child(2) { animation-delay: 0.2s; }
.group-tour-grid .group-tour-card:nth-child(3) { animation-delay: 0.3s; }
.group-tour-grid .group-tour-card:nth-child(4) { animation-delay: 0.4s; }
.group-tour-grid .group-tour-card:nth-child(5) { animation-delay: 0.5s; }
.group-tour-grid .group-tour-card:nth-child(6) { animation-delay: 0.6s; }
.group-tour-grid .group-tour-card:nth-child(7) { animation-delay: 0.7s; }
.group-tour-grid .group-tour-card:nth-child(8) { animation-delay: 0.8s; }
.group-tour-grid .group-tour-card:nth-child(9) { animation-delay: 0.9s; }
.group-tour-grid .group-tour-card:nth-child(10) { animation-delay: 1.0s; }
.group-tour-grid .group-tour-card:nth-child(11) { animation-delay: 1.1s; }
.group-tour-grid .group-tour-card:nth-child(12) { animation-delay: 1.2s; }

.status-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 0.85em;
  font-weight: bold;
  z-index: 3;
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
}

.status-not-started {
  background-color: #607d8b; /* Blue Grey */
}

.status-registering {
  background-color: #4CAF50; /* Green */
}

.status-registration-closed {
  background-color: #FFC107; /* Amber */
  color: #333;
}

.status-in-progress {
  background-color: #2196F3; /* Blue */
}

.status-ended {
  background-color: #F44336; /* Red */
}

.status-default {
  background-color: #9E9E9E; /* Grey */
}
</style>